package com.pai4j.common.service;

import com.aliyun.oss.event.ProgressEvent;
import com.aliyun.oss.event.ProgressEventType;
import com.aliyun.oss.event.ProgressListener;
import com.chat4j.common.util.web.SpringContextUtil;
import org.apache.commons.lang3.StringUtils;

/**
 * @Author: 程序员七七
 * @Date: 31.12.21 10:45 下午
 * 上传进度监听器
 */
public class PutObjectProgressListener implements ProgressListener {

    private long bytesWritten = 0;

    private long totalBytes = -1;

    private boolean succeed = false;

    /***
     * 任务ID
     */
    private String taskId;

    /***
     * 监听上传进度
     * @param progressEvent
     */
    @Override
    public void progressChanged(ProgressEvent progressEvent) {
        if (StringUtils.isBlank(taskId)) {
            return;
        }
        long bytes = progressEvent.getBytes();
        ProgressEventType eventType = progressEvent.getEventType();
        switch (eventType) {
            case TRANSFER_STARTED_EVENT:
                System.out.println("Start to upload......");
                // 0 表示开始上传
                this.updateProgressCache(taskId, 1);
                break;
            case REQUEST_CONTENT_LENGTH_EVENT:
                this.totalBytes = bytes;
                System.out.println(this.totalBytes + " bytes in total will be uploaded to OSS");
                break;
            case REQUEST_BYTE_TRANSFER_EVENT:
                this.bytesWritten += bytes;
                int percent = (int)(this.bytesWritten * 100.0 / this.totalBytes);
                System.out.println(bytes + " bytes have been written at this time, upload progress: " + percent + "%(" + this.bytesWritten + "/" + this.totalBytes + ")");
                this.updateProgressCache(taskId, percent);
                break;
            case TRANSFER_COMPLETED_EVENT:
                this.succeed = true;
                System.out.println("Succeed to upload, " + this.bytesWritten + " bytes have been transferred in total");
                // 100 表示上传完成
                this.updateProgressCache(taskId, 100);
                break;
            case TRANSFER_FAILED_EVENT:
                System.out.println("Failed to upload, " + this.bytesWritten + " bytes have been transferred");
                // -1 表示上传失败
                this.updateProgressCache(taskId, -1);
                break;
            default:
                break;
        }
    }

    public boolean isSucceed() {
        return succeed;
    }

    PutObjectProgressListener(String taskId, long totalBytes) {
        this.taskId = taskId;
        this.totalBytes = totalBytes;
        if (StringUtils.isNotBlank(taskId)) {
            updateProgressCache(taskId, 0);
        }
    }

    private void updateProgressCache(String taskId, int percent) {
        PutObjectProgressCacheService progressCacheService = SpringContextUtil.getBean(PutObjectProgressCacheService.class);
        progressCacheService.set(taskId, percent);
    }
}
